
#首页视图函数
import logging
from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import redis_store
from info.models import User, News, Category
from info.modules.index import index_bule

#index视图函数
from utils.commons import user_login_data
from utils.response_code import RET


@index_bule.route('/',methods=['get','post'])
@user_login_data
def index():
    #得到session的user_id
    # user_id=session.get("user_id")

    #查询点击量前十的新闻
    try:
        news_list=News.query.order_by(News.clicks).limit(10).all()
    except  Exception as e:
        logging.error(e)

    #将新闻对象的信息添加到列表
    click_news_list=[]
    for new in news_list:
        click_news_list.append(new.to_dict())

    #查询所有新闻的分类信息
    try:
        categories = Category.query.all()
    except Exception as e:
        logging.error(e)

    #将分类的信息存入列表中
    category_list=[]
    for category in categories:
        category_list.append(category.to_dict())

    # user=None
    # 得到对象
    # if user_id:
    #     user = User.query.filter(User.id == user_id).first()


    dict_data={
        "user_info": g.user.to_dict() if g.user else "" ,  #用户信息
        "click_news_list":click_news_list ,  #热门新闻排行
        "categories": category_list
    }
    return render_template('news/index.html', data=dict_data)

#返回网页图标
@index_bule.route('/favicon.ico')
def get_logo():
    return current_app.send_static_file("news/favicon.ico")



@index_bule.route('/newslist')
@user_login_data
def newslist():
    #获取类型id，第几页，每页几条
    cid=request.args.get("cid","1")
    page=request.args.get("page","1")
    per_page=request.args.get("per_page","5")

    #将字符串转数字，便于查询
    try:
        page=int(page)
        per_page=int(per_page)
    except :
        page=1
        per_page=5

    #如果是查询最新新闻，则将过滤字符串设为“”就行
    condition=""
    if cid!="1":
        condition=(News.category_id==cid)

    #查询对应新闻
    try:
        paginate=News.query.filter(condition).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        logging.error(e)
        return  jsonify(errno=RET.DBERR,errmsg="获取新闻失败")

    #将新闻对象的详细信息添加到列表
    newList=[]
    for new in paginate.items:
        newList.append(new.to_dict())

    #当前页
    currentPage=paginate.page
    #总页数
    totalPage =paginate.pages

    return jsonify(errno=RET.OK,errmsg="获取成功",newsList=newList,currentPage=currentPage,totalPage=totalPage)